<template>
  <van-cell-group class="upload-box">
    <!-- 上传文件 -->
    <van-cell class="custom-file-upload">
      <template #title>
        <span class="custom-title">附件（{{ attachmentList.length }}个）</span>
        <div v-if="maxCount * 1 && attachmentList.length < maxCount * 1">
        <van-uploader v-if="editAble" accept="*" :before-read="beforeRead" :after-read="afterRead">
          <!-- <van-icon name="plus" />上传 -->
        </van-uploader>
      </div>
      <div>
        <van-uploader v-if="editAble" accept="*" :before-read="beforeRead" :after-read="afterRead"></van-uploader>
      </div>
      </template>
      <!-- <template #default v-if="maxCount * 1 && attachmentList.length < maxCount * 1">
        <van-uploader v-if="editAble" accept="*" :before-read="beforeRead" :after-read="afterRead"><van-icon name="plus" />上传</van-uploader>
      </template>
      <template #default>
        <van-uploader v-if="editAble" accept="*" :before-read="beforeRead" :after-read="afterRead"></van-uploader>
      </template>-->
      <template #label> 
        <span class="custom-tip" v-if="editAble">注：支持png/jpg/PDF/word/excel，小于50M，最多4个。</span>
        <div class="custom-file-list">
          <!-- 文件列表 -->
          <div class="custom-file-item" v-for="(fitem, index) in attachmentList" :key="`file_${index}`">
            <div class="file-info" @click="clickFile(fitem)">
              <div class="file-image">
                <template v-if="fitem.fileType.indexOf('image') > -1">
                  <van-image width="50" height="50" :radius="4" :src="fitem.fileUrl" />
                </template>
                <div class="file-type" v-else-if="fitem.fileType === 'application/pdf'">
                  <span class="iconfont icon-pdf-fill"></span>
                  <img :src="enclosureImg" alt="" class="enclosure-img" />
                </div>
                <div class="file-type" v-else-if="fitem.fileType === 'application/msword'">
                  <img :src="enclosureImg" alt="" class="enclosure-img" />
                </div>
                <div class="file-type" v-else-if="/\.(doc|docx)$/.test(fitem.fileName)">
                  <img :src="enclosureImg" alt="" class="enclosure-img" />
                </div>
                <div class="file-type" v-else-if="fitem.fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'">
                  <img :src="enclosureImg" alt="" class="enclosure-img" />
                </div>
              </div>
              <div class="file-tit">
                <div>{{ fitem.fileName }}</div>
                <div class="file-size" v-if="fitem.fileSize">{{ fileSizeFn(fitem.fileSize) }}</div>
              </div>
            </div>
            <div class="file-arrow" v-if="preview">
              <van-icon v-if="editAble" name="delete-o" @click="deleteFile(index)" />
              <div v-else style="min-width: 26px" @click="clickFilePreview(fitem)">预览</div>
            </div>
            <div class="file-arrow" v-else>
              <van-icon v-if="editAble" name="delete-o" @click="deleteFile(index)" />
              <div v-else style="min-width: 26px" @click="clickFile(fitem)">下载</div>
            </div>
          </div>
        </div>
      </template>
    </van-cell>
  </van-cell-group>
</template>

<script>
import { ImagePreview } from 'vant'
import { isInIOS } from '@/utils/utils'
import { Base64 } from 'js-base64'
export default {
  name: 'uploadFile',
  props: {
    editAble: {
      // 该属性控制是否可以上传和删除文件，如果为false，则不显示上传和删除按钮
      type: Boolean,
      default: true
    },
    attachmentList: {
      // 附件列表
      type: Array,
      default: () => []
    },
    maxCount: {
      type: [String, Number],
      default: ''
    },
    paramData: {
      type: Object,
      default: () => {}
    },
    preview: {
      // 是否预览来的
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      enclosureImg: require('@/assets/enclosure.png'),
      mimeType: ['xlsx', 'doc', 'image/png', 'image/jpeg', 'image/gif', 'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel']
    }
  },
  methods: {
    beforeRead(file) {
      if (this.mimeType.indexOf(file.type) > -1 && file.size <= 50 * 1024 * 1024) {
        return true
      } else {
        this.$toast('附件只支持png/jpg/PDF/word/excel，小于50M')
        return false
      }
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file)
      this.upload(file.file)
    },
    fileSizeFn(fileSize) {
      fileSize = +fileSize
      return fileSize < 1024 * 1024 ? `${(fileSize / 1024).toFixed(2)}KB` : `${(fileSize / 1024 / 1024).toFixed(2)}MB`
    },
    // 开始上传
    upload(fileObj) {
      let { name: fileName, size: fileSize, type: fileType } = fileObj
      const token = new Date().getTime()
      const fileItem = {
        fileType,
        fileName,
        fileSize,
        uploadPercent: 0,
        fileUrl: '',
        token
      }
      // 不使用七牛上传部分
      let formData = new FormData()
      formData.append('file', fileObj)
      this.$Posting(this.$api.uploadFile, formData, { headers: { 'Content-Type': 'multipart/form-data' } })
        .then((res) => {
          if (res.isSuccess) {
            console.log('上传成功：', res.data)
            fileItem.fileUrl = res.data.accessUrl
            fileItem.uploadPercent = 100
            this.$emit('uploadFileComplete', fileItem)
          } else {
            this.$emit('文件上传失败')
          }
        })
        .catch(() => {
          this.$emit('文件上传失败')
        })
    },
    deleteFile(fitem) {
      this.$emit('deleteFile', fitem)
    },
    clickFile(fitem) {
      // 点击文件操作，如果是图片则预览
      if (fitem.fileType.indexOf('image') > -1) {
        ImagePreview([fitem.fileUrl])
      } else {
        this.download(fitem)
      }
    },
    loadUrl() {
      // 导入UIWebview、NSURLRequest、NSURL类
      this.$toast('=================》')
      plus.ios.importClass('UIWebview')
      const NSURLRequest = plus.ios.import('NSURLRequest')
      const NSURL = plus.ios.import('NSURL')
      // 获取当前Webview对象的实例
      const wv = plus.ios.currentWebview()
      // 创建请求对象
      const req = NSURLRequest.requestWithURL(NSURL.URLWithString('https://www.baidu.com'))
      // 跳转页面
      plus.ios.invoke(wv, 'loadRequest:', req)
      // 释放对象(可选)
      plus.ios.deleteObject(req)
      plus.ios.deleteObject(wv)
    },
    download(fitem) {
      // debugger
      const downUrl = fitem.fileUrl
      let _this = this
      try {
        // https://jingyan.baidu.com/article/4e5b3e191344d191901e24a4.html
        // _this.$toast('下载开始')
        let dtask = plus.downloader.createDownload(downUrl)
        // _this.$toast('无法打开此文件：' + JSON.stringify(dtask))
        let w = plus.nativeUI.showWaiting('开始下载...')
        dtask.addEventListener(
          'statechanged',
          function (task, status) {
            switch (task.state) {
              case 3: // 已接收到数据
                // _this.$toast('下载接收数据中')
                if (w) {
                  w.setTitle('数据下载中：' + task.downloadedSize + '/' + task.totalSize)
                }
                break
              case 4: // 下载完成
                if (status === 200) {
                  // _this.$toast('下载成功')
                  if (w) {
                    w.close()
                  }
                  plus.runtime.openFile(task.filename, {}, function (e) {
                    _this.$toast('无法打开此文件：' + e.emssage)
                  })
                } else {
                  _this.$toast('下载失败：' + status)
                  plus.nativeUI.closeWaiting()
                }
                break
            }
          },
          false
        )
        dtask.start()
      } catch (err) {
        // 浏览器的方式下载
        // alert('https://cycy.tjcyfz.com/filePreview/onlinePreview?url=' + encodeURIComponent(Base64.encode(downUrl)))
        // window.open(downUrl, '_blank')
        // return
        if (isInIOS()) {
          // ios手机下会直接打开文件，打开后又回不到app，所以用window.open打开
          // if (this.preview && fitem.fileWord) {
          //   // 预览时，如果是预览来的
          //   window.open(fitem.fileWord, '_blank')
          //   // window.location.href = fitem.fileWord
          //   // plus.runtime.openURL(fitem.fileWord)
          //   return
          // }
          if (downUrl) {
            // plus.runtime.openFile(downUrl, {}, function (e) {
            //   _this.$toast('无法打开此文件：' + e.message)
            // })
            // window.location.href = window.location.origin + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(downUrl))
            // window.location.href = 'https://cycy.tjcyfz.com/filePreview/onlinePreview?url=' + encodeURIComponent(Base64.encode(downUrl))
            if (window.location.host === 'cycy.tjcyfz.com') {
              window.location.href = 'https://cycy.tjcyfz.com/filePreview/onlinePreview?url=' + encodeURIComponent(Base64.encode(downUrl))
            } else {
              window.open(fitem.fileWord, '_blank')
            }

            // plus.webview.open('https://www.baidu.com')
            // _this.loadUrl()
            // plus.runtime.openURL(downUrl)
            // window.location.href = downUrl
            // window.open(downUrl, '_blank')
          }
        } else {
          const eleLink = document.createElement('a')
          eleLink.download = fitem.fileName
          eleLink.style.display = 'none'
          // 字符内容转变成blob地址
          // const blob = new window.Blob([downUrl])
          // eleLink.href = URL.createObjectURL(blob)
          eleLink.href = downUrl
          eleLink.target = '_blank'
          // 触发点击
          document.body.appendChild(eleLink)
          eleLink.click()
          // 然后移除
          document.body.removeChild(eleLink)
        }
      }
    },
    clickFilePreview(fitem) {
      // window.location.href = 'http://106.54.32.100:9112/onlinePreview?url=aHR0cDovLzEwNi41NC4zMi4xMDA6OTExMi9kZW1vL2RlZmF1bHQoMSkuZG9j'
      // this.$router.push({
      //   path: '/contractPriveView'
      //   // query: {
      //   //   pdfUrl: encodeURIComponent(res.data.pdfUrl)
      //   // }
      // })
      // return
      const param = {
        contractId: this.paramData.id,
        contractType: 8,
        templateUrl: fitem.fileUrl,
        filename: fitem.fileName
      }
      this.$Posting(this.$api.generateContract, param).then((res) => {
        if (res.code === '0') {
          const result = {
            fileUrl: res.data.pdfUrl,
            // fileUrl: 'https://cycy.tjcyfz.com/fileWeb/file/fs/group1/M00/00/1B/wKhbFWeLdQaAVBlNAAWbhzUSopg354.pdf?v=1737192710189',
            fileName: fitem.fileName,
            fileType: fitem.fileType,
            fileWord: res.data.wordUrl
          }
          // this.$router.push({
          //   path: '/contractPriveView',
          //   query: {
          //     pdfUrl: encodeURIComponent(res.data.pdfUrl)
          //   }
          // })
          this.clickFile(result)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
// 样式在 assets/styles/custom.less里
.upload-box {
  ::v-deep .van-collapse .van-cell {
    height: auto !important;
  }
  ::v-deep .van-cell__label {
    color: #567df4;
  }

  .enclosure-img {
    width: 50px;
    height: 50px;
  }

  ::v-deep .van-cell__title {
    width: 100%;
    flex: none;
  }

  .custom-file-list {
    .custom-file-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .file-info {
        display: flex;
        overflow: hidden;

        .file-type {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50px;
          height: 50px;
        }

        .file-tit {
          flex: 1;
          overflow: hidden;
          padding: 4px 0 0 10px;
          color: rgba(0, 0, 0, 0.65);
          line-height: 22px;

          .file-name {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          .file-op {
            color: #999;
            margin: 16px 0 0;
            display: flex;
            align-items: center;

            .file-btns {
              margin-left: 20px;

              > span {
                color: var(--primary-color);
                cursor: pointer;
                margin-right: 20px;

                &:last-child {
                  margin-right: 0;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
